package sz.szsmk.citizencard.mvp.presenter;

import android.util.Log;
import android.widget.Toast;

import com.google.gson.Gson;
import com.squareup.okhttp.Request;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import javax.annotation.Nullable;
import javax.inject.Inject;

import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import sz.szsmk.citizencard.DaggerApplication;
import sz.szsmk.citizencard.gover.FunctionItem;
import sz.szsmk.citizencard.log.L;
import sz.szsmk.citizencard.model.network.GsdxNetApi;
import sz.szsmk.citizencard.model.network.RxSubscribers;
import sz.szsmk.citizencard.model.network.bean.request.AccessTokenRequest;
import sz.szsmk.citizencard.model.network.bean.request.SimpleReq;
import sz.szsmk.citizencard.model.network.bean.response.BaseBean;
import sz.szsmk.citizencard.model.network.bean.response.CheckIsChargeRes;
import sz.szsmk.citizencard.model.network.bean.response.CloudFlashRes;
import sz.szsmk.citizencard.model.network.bean.response.SeleciUserAuthRes;
import sz.szsmk.citizencard.model.network.bean.response.SimpleRes;
import sz.szsmk.citizencard.model.network.bean.response.UserBean;
import sz.szsmk.citizencard.model.network.dzbean.req.CommonRequest;
import sz.szsmk.citizencard.model.network.dzbean.req.GetOpenIdReq;
import sz.szsmk.citizencard.model.network.dzbean.req.PreAuthThiedReq;
import sz.szsmk.citizencard.model.network.dzbean.req.PreAuthThirdRes;
import sz.szsmk.citizencard.model.network.dzbean.req.QueryDzsmkAgreementReq;
import sz.szsmk.citizencard.model.network.dzbean.res.CheckIsRealName2Res;
import sz.szsmk.citizencard.model.network.dzbean.res.CheckIsRealNameRes;
import sz.szsmk.citizencard.model.network.dzbean.res.GetOpenIdRes;
import sz.szsmk.citizencard.model.network.dzbean.res.PreAuthResult;
import sz.szsmk.citizencard.model.network.dzbean.res.QueryDzsmkAgreeMentRes;
import sz.szsmk.citizencard.mvp.contract.IGoverContact;
import sz.szsmk.citizencard.mvp.contract.IMainContact;
import sz.szsmk.citizencard.mvp.contract.ISearchAllContact;
import sz.szsmk.citizencard.retrofitrxjava.DZSmkAppInit;
import sz.szsmk.citizencard.retrofitrxjava.ErrorAction;
import sz.szsmk.citizencard.retrofitrxjava.NetworkDateSources;
import sz.szsmk.citizencard.retrofitrxjava.SubscribeResult;
import sz.szsmk.citizencard.retrofitrxjava.newversion.ApiCallback;
import sz.szsmk.citizencard.retrofitrxjava.newversion.HttpDateSource;
import sz.szsmk.citizencard.retrofitrxjava.newversion.NewHttpApi;
import sz.szsmk.citizencard.smkretrofit.NetworkDateSource;
import sz.szsmk.citizencard.ui.activity.IMainActivity;
import sz.szsmk.citizencard.util.ACache;
import sz.szsmk.citizencard.util.Constant;
import sz.szsmk.citizencard.util.ObjectSignatureUtil;
import sz.szsmk.citizencard.widget.GlobalVariables;

/**
 * Copyright (c)2019
 * author: zdh
 * created on: 2019/1/8 20:03
 * description:
 */
public class SearchAllPresenter extends IBasePresenter
        implements ISearchAllContact.ISearchAllPresenter<ISearchAllContact.ISearchAllView> {

    private NetworkDateSources mNetworkDateSource;
    private NetworkDateSource mNetworkDateSources;
    GsdxNetApi gsdxNetApi;

    @Inject
    public SearchAllPresenter(GsdxNetApi gsdxNetApi) {
        this.gsdxNetApi = gsdxNetApi;
        this.mNetworkDateSources =NetworkDateSource.getInstance();
        this.mNetworkDateSource = NetworkDateSources.getInstance();
    }


    @Override
    public void getAll(String type, String keyWord, int currentPager) {
        SimpleReq simpleReq = new SimpleReq();
        simpleReq.setKey_type(type);
        Log.i("信息",keyWord);
        simpleReq.setKey_words(keyWord);
        simpleReq.setPage_num(currentPager);
        simpleReq.setPage_size(15);
        String json = new Gson().toJson(simpleReq);
        mNetworkDateSource.simple(simpleReq, new SubscribeResult<SimpleRes>() {
            @Override
            protected void onOk(SimpleRes response) {
                String json = new Gson().toJson(response);
                ((ISearchAllContact.ISearchAllView) mView).getAllSucc(response.getResult());
            }

            @Override
            protected void onFailure(SimpleRes response) {
                super.onFailure(response);
                ((ISearchAllContact.ISearchAllView) mView).getAllFail(response);
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {

            }
        });


    }

    @Override
    public void checkSuccessOrderStatus(String access_token) {
        OkHttpUtils.post()
                .url(Constant.BASE_URL + "app/supply/CheckSuccessOrderStatusReq")
                .addParams("access_token", access_token)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Request request, Exception e) {
                    }

                    @Override
                    public void onResponse(String response) {
                        CloudFlashRes cloudFlashRes = new Gson().fromJson(response, CloudFlashRes.class);
                        if (cloudFlashRes != null) {
                            if (mView != null) {
                                String code = cloudFlashRes.getCode();
                                if (code.equals("000000")) {
                                    String orderStatus = cloudFlashRes.getOrderStatus();
                                    if (orderStatus != null) {
                                        ACache.get(DaggerApplication.getIns()).put("orderStatus", orderStatus);
                                    }
                                    ACache.get(DaggerApplication.getIns()).put("orderStatus", orderStatus);
                                    ((ISearchAllContact.ISearchAllView) mView).checkSuccessOrderStatusSucc(orderStatus);
                                } else {
                                    ((ISearchAllContact.ISearchAllView) mView).checkSuccessOrderStatusFail(cloudFlashRes);
                                }
                            }

                        }
                    }
                });
    }
    private GetOpenIdRes getOpenIdRes;
    @Override
    public void getOpenId() {

        GetOpenIdReq getOpenIdReq = new GetOpenIdReq();
        String access_token = ACache.get(DaggerApplication.getIns()).getAsString("access_token");
        getOpenIdReq.setUser_type(0);
        getOpenIdReq.setAccess_token(access_token);
        String s = new Gson().toJson(getOpenIdReq);
        L.e(Constant.TAG, "getOpenid----" + s);
        gsdxNetApi.getOpenId(getOpenIdReq)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new RxSubscribers<GetOpenIdRes>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    protected void _onNext(GetOpenIdRes response) {
                        getOpenIdRes = response;
                        String json = new Gson().toJson(response);
                        L.e(Constant.TAG, "getOpenId---->" + json);
                        String openId = response.getOpenId();
                        ACache.get(DaggerApplication.getIns()).remove("openId");
                        ACache.get(DaggerApplication.getIns()).put("openId", openId + "");
                        ACache.get(DaggerApplication.getIns()).put("userId", response.getUserId() + "");
                        PreAuthResult preAuthResult = new PreAuthResult();
                        preAuthResult.setOpenId(response.getOpenId());
                        GlobalVariables.getInstance(DZSmkAppInit.getInstance().getContext()).setPreAuthResult(DaggerApplication.getIns(), preAuthResult);
                        String openId1 = GlobalVariables.getInstance(DZSmkAppInit.getInstance().getContext()).getPreAuthResult().getOpenId();

//                        PreAuthResult preAuthResult = GlobalVariables.getInstance(DZSmkAppInit.getInstance().getContext()).getPreAuthResult();
//                        String token = preAuthResult.getToken();
//                        PreAuthResult authResult = GlobalVariables.getInstance(DZSmkAppInit.getInstance().getContext()).getPreAuthResult();
//                        PreAuthResult authResult = GlobalVariables.getInstance().getPreAuthResult();

//                        authResult.setOpenId(openId);

                        //2.获取到openid后登陆

//                        queryDzsmkAgreement(openId);
                        if (response.getCode().equals("000000")) {
                            ((ISearchAllContact.ISearchAllView) mView).getOpenIdSucc(response);
                        } else {
                            ((ISearchAllContact.ISearchAllView) mView).getOpenIdFail(response);
                        }
                    }

                    @Override
                    protected void _onError(String message) {
                        Log.e("zdh", "请求失败" + message);
                    }
                });
    }

    @Override
    public void checkIsOpenElecCard(String openId) {

        CommonRequest request = new CommonRequest();
        request.setOpenId(openId);
        ObjectSignatureUtil.signaturePreAuthRequest(request);
        String toJson = new Gson().toJson(request);
        L.e(Constant.TAG, "checkIsRealName------>" + toJson);

        addSubscription(HttpDateSource.INSTANCE.createApi(NewHttpApi.class, Constant.DZ_BASE_URL).checkIsRealName(request), new ApiCallback<CheckIsRealName2Res>() {
            @Override
            public void onSuccess(@Nullable CheckIsRealName2Res response) {
                if (response.getCode().equals("0000")) {
                    ((ISearchAllContact.ISearchAllView) mView).checkIsOpenElecCardSuccess(response);
                } else {
                    ((ISearchAllContact.ISearchAllView) mView).checkIsOpenElecCardError(response);
                }
            }
            @Override
            public void onFailure(@Nullable BaseBean model, @Nullable Throwable e) {
            }
        });


//        mNetworkDateSources.checkIsRealName(request, new Action1<CheckIsRealNameRes>() {
//            @Override
//            public void call(CheckIsRealNameRes preAuthRes) {
//                String json = new Gson().toJson(preAuthRes);
//                if (preAuthRes.getCode().equals("0000")) {
//                    ((ISearchAllContact.ISearchAllView) mView).checkIsOpenElecCardSuccess(preAuthRes);
//                } else {
//                    ((ISearchAllContact.ISearchAllView) mView).checkIsOpenElecCardError(preAuthRes);
////                    PubUtils.popTipOrWarn(DaggerApplication.getIns(),preAuthRes.getMessage() );
//                }
//            }
//        }, new ErrorAction() {
//            @Override
//            public void onCall(Throwable throwable) {
////                ((IMainContact.IMainView) mView).checkIsOpenElecCardError(preAuthRes);
//                L.e(Constant.TAG, "--------------------" + throwable.getMessage());
//            }
//        });
    }

    public void preAuthThird(String openId, final String id) {
        PreAuthThiedReq preAuthThiedReq = new PreAuthThiedReq();
        preAuthThiedReq.setMobileNumber(getOpenIdRes.getMobile() + "");
        preAuthThiedReq.setOpenId(openId);
        preAuthThiedReq.setUserId(getOpenIdRes.getUserId() + "");
        preAuthThiedReq.setPhotoUrl("");
        String channelId = ACache.get(DaggerApplication.getIns()).getAsString("channelId");
        preAuthThiedReq.setChannelId(channelId);

        ObjectSignatureUtil.signaturePreAuthRequest(preAuthThiedReq);
        String toJson = new Gson().toJson(preAuthThiedReq);
        L.e(Constant.TAG, "------->" + toJson);
        mNetworkDateSources.preAuthThird(preAuthThiedReq, new Action1<PreAuthThirdRes>() {
            @Override
            public void call(PreAuthThirdRes preAuthRes) {
                String code = preAuthRes.getCode();
                if (code.equals("0000")) {
                    PreAuthThirdRes.DataBean data = preAuthRes.getData();
                    String json = new Gson().toJson(data);
                    ACache.get(DaggerApplication.getIns()).put("token", preAuthRes.getData().getToken());
                    PreAuthResult preAuthResult = new Gson().fromJson(json, PreAuthResult.class);
                    GlobalVariables.getInstance(DZSmkAppInit.getInstance().getContext()).setPreAuthResult(DaggerApplication.getIns(), preAuthResult);
                    PreAuthResult authResult = GlobalVariables.getInstance(DZSmkAppInit.getInstance().getContext()).getPreAuthResult();
                    String token = authResult.getToken();
                    ((ISearchAllContact.ISearchAllView) mView).preAuthThirdSucc(id);
                    L.e(Constant.MTAG, "存储的token：" + token);

                } else {
                    ((ISearchAllContact.ISearchAllView) mView).preAuthThirdFail(preAuthRes);
                }


            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {
                L.e(Constant.TAG, "--------------------" + throwable.getMessage());
            }
        });

    }
    @Override
    public void queryDzsmkAgreement(final String openId) {

//        ACache.get(DaggerApplication.getIns()).put("channelId", "000001");
        QueryDzsmkAgreementReq queryDzsmkAgreementReq = new QueryDzsmkAgreementReq();
        queryDzsmkAgreementReq.setOpenId(openId);
        queryDzsmkAgreementReq.setUserType(0);
        String json = new Gson().toJson(queryDzsmkAgreementReq);
        L.e(Constant.TAG, "queryDzsmkAgreement---->" + json);
        mNetworkDateSource.queryDzsmkAgreement(queryDzsmkAgreementReq, new SubscribeResult<QueryDzsmkAgreeMentRes>() {
            @Override
            protected void onOk(QueryDzsmkAgreeMentRes response) {
                String toJson = new Gson().toJson(response);
                String channelId = response.getChannelId();
                ACache.get(DaggerApplication.getIns()).put("channelId", channelId);
                L.e(Constant.TAG, "queryDzsmkAgreement---->" + toJson);
                preAuthThird(openId, "2");
//                preAuthThird(openId, openId);
//                ((IMainContact.IMainView) mView).queryDzsmkAgreementSucc();
            }

            @Override
            protected void onFailure(QueryDzsmkAgreeMentRes response) {
                super.onFailure(response);
                if (response.getCode().equals("000005")) {
                    ACache.get(DaggerApplication.getIns()).put("channelId", "000003");
                    preAuthThird(openId, "2");
                }
                ((ISearchAllContact.ISearchAllView) mView).queryDzsmkAgreementFail(response);
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {

            }
        });
    }

    @Override
    public void checkIsCharge() {
//        CommonRequest commonRequest = ObjectSignatureUtil.getCommonRequest();
        CommonRequest commonRequest = new CommonRequest();
        String openId = ACache.get(DaggerApplication.getIns()).getAsString("openId");
        commonRequest.setOpenId(openId);

        ObjectSignatureUtil.signatureZhsz(commonRequest, "");
        String json = new Gson().toJson(commonRequest);
        L.e(Constant.TAG, "checkIsCharge-----" + json);
        mNetworkDateSources.checkIsCharge(commonRequest, new Action1<CheckIsChargeRes>() {
            @Override
            public void call(CheckIsChargeRes ibaseBean) {
                String toJson = new Gson().toJson(ibaseBean);
                L.e(Constant.TAG, "checkIsCharge--->" + toJson);
                ((ISearchAllContact.ISearchAllView) mView).checkIsChargeSucc(ibaseBean);
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {
                ((ISearchAllContact.ISearchAllView) mView).checkIsChargeFail();
            }
        });
    }


    @Override
    public void selectUserAuth(final String type) {
        AccessTokenRequest accessTokenRequest = new AccessTokenRequest();
        mNetworkDateSource.selectUserAuth(accessTokenRequest, new SubscribeResult<SeleciUserAuthRes>() {
            @Override
            protected void onOk(SeleciUserAuthRes response) {
                ((ISearchAllContact.ISearchAllView) mView).selectUserAuthSucc(response,type);
            }

            @Override
            protected void onFailure(SeleciUserAuthRes response) {
                super.onFailure(response);
                Toast.makeText(DaggerApplication.getIns(), response.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }, new ErrorAction() {
            @Override
            public void onCall(Throwable throwable) {

            }
        });
    }

}
